package com.chenhui.myneighbors.controller;

import com.chenhui.myneighbors.entity.User;
import com.chenhui.myneighbors.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserHandler {

    @Autowired
    private UserRepository  userRepository;

    public UserHandler(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping("/findAll/{page}/{size}")
    public Page<User> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        Pageable pageable= PageRequest.of(page-1,size);
        return userRepository.findAll(pageable);
    }

    @PostMapping("/save")
    public String save(@RequestBody  User user){
        User saved=userRepository.save(user);
        if (saved!=null){
           return "success";
        }else {
            return "error";
        }
    }

    @GetMapping("/findById/{id}")
    public User findById(@PathVariable("id") Integer id){
        return userRepository.findById(id).get();
    }

    @PutMapping("/update")
    public String update(@RequestBody User user){
        User saved=userRepository.save(user);
        if (saved!=null){
            return "success";
        }else {
            return "error";
        }
    }
}
